--local list = list or require"list"

module(...,package.seeall)

eventsystem_mt = {
  post = function(self, event)
    if self:filter(event) ~= true then  
      self.events:pushright(event)
      self:report(event)
    end  
  end,
  filter = function(self,event)
    return false -->don't filter out
  end,
  report = function(self,event)
    local l,e,w,s
    for l,e in pairs (self.listeners) do
      for w,s in pairs(e) do
        if compare(event[w],s) then
          l:handle("onevent",event)
          return
        end
      end    
    end
  end,
  addlistener = function(self,listener,who,when,where,what,why)
    self.listeners[listener] = { who = who, when = when, where = where, what = what, why = why}
  end,
  removelistener = function(self,listener)
    self.listeners[listener] = nil
  end,
  getsnapshot = function(self)
    return readonly(self.events)
  end,  
  clear = function (self)
    self.events = list.new()
  end,
  __index = function(t,k)
    return getmetatable(t)[k]
  end,  
}

new = function()
  local es = {}
  es.events = list.new()
  es.listeners = {}
  setmetatable(es,eventsystem_mt)
  return es
end

serialize = function(eventtable)
  local snap ={}
  for e in list.entries(self.events) do
    table.insert(snap,format("%s,%s,%s,%s,%s\n",tostring(e.who),tostring(e.when),tostring(e.where),tostring(e.what),tostring(e.why)))
  end
  snap = table.concat(snap, "\n") .. "\n"
  return snap
end

--event("me",now,here,"","")
--maineventsystem:addlistener(t,"*","*","*","*","*")
--event("you",now,here,"","")
--print(maineventsystem:getsnapshot())
--maineventsystem:clear()
--print(maineventsystem:getsnapshot())
